﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MethodWorx.CMS.Plugins;
using MethodWorx.CMS.Services;
using MethodWorx.CMS.Workflow.CreateMember;
using MethodWorx.Core.DomainModel;
using MethodWorx.Core.Validation;
using MethodWorx.CMS.Content;

namespace MethodWorx.CMS.Workflow.SetAttribute
{
    public class SetAttributeWorkflowComponent : WorkflowComponent<SetAttributeConfigurationController>
    {
        public SetAttributeWorkflowComponent(Plugin plugin)
            : base(plugin)
        {
        }

        public static Guid ComponentId = Guid.Parse("{8BA00E89-A1A6-4DA6-A5F1-85838DDB435D}");

        public override Guid Id
        {
            get { return ComponentId;  }
        }

        public override string Category
        {
            get { return "Data";  }
        }

        public override string Name
        {
            get { return "Set Attribute";  }
        }

        public override string Description
        {
            get { return "Sets an attribute of an entity";  }
        }

        public override string View
        {
            get { return "SetAttributeConfigurationView.ascx"; }
        }

        public override StepExecutionResult Execute(IWorkflowExecutionContext context, IWorkflowConfiguration configuration)
        {
            //
            //  ok, we can do this regardless of the validation state of the view
            var config = configuration as SetAttributeConfiguration;
            var entity = context.GetWorkflowValue(config.Variable);
            if(entity != null && entity is IAttributes && entity is AggregateRoot)
            {
                //
                //  ok, can we save it now
                ((IAttributes)entity).SetAttribute(config.Attribute, this.ParseString(config.Value, context.GetAllWorkflowValues()));
                //  save it via the attribute service
                using(var uow = context.CmsDataProvider.GetUnitOfWorkFactory().Begin())
                {
                    uow.RegisterChanged((AggregateRoot)entity);
                    uow.Commit();
                }
            }

            return StepExecutionResult.Ok();

        }
    }
}
